import { Component, ChangeDetectorRef } from "@angular/core";
import { NavController, NavParams, ActionSheetController } from "ionic-angular";
import { DailyInspectionBean } from "./bean/daily-inspection.bean";
import { Storage } from "@ionic/storage";
import { HttpService } from "../../providers/http.service";
import { Camera, CameraOptions } from "@ionic-native/camera";
import { CommonFunc } from "../../providers/commonFunc";
import { WorkSumPage } from "../work-sum/work-sum";
import { appConfig } from "../../providers/config";
import {
  FileTransfer,
  FileUploadOptions,
  FileTransferObject
} from "@ionic-native/file-transfer";
import { File } from "@ionic-native/file";
import * as moment from "moment";
import { PhotoViewer } from "@ionic-native/photo-viewer";

@Component({
  selector: "page-daily-inspection",
  templateUrl: "daily-inspection.html"
})
export class DailyInspectionPage {
  private showOK: boolean = false;
  private showError: boolean = false;
  private appConfig: any;
  private dailyInspectionBean: DailyInspectionBean = new DailyInspectionBean();
  private user: any;
  constructor(
    public navCtrl: NavController,
    private storage: Storage,
    private httpService: HttpService,
    private camera: Camera,
    private commonFunc: CommonFunc,
    private transfer: FileTransfer,
    private file: File,
    private navParams: NavParams,
    private photoViewer: PhotoViewer,
    private ActionSheet: ActionSheetController,
    public cd: ChangeDetectorRef
  ) {
    this.appConfig = appConfig;
    this.storage.get("user").then(data => {
      this.user = data;
    });
  }
  doOk(name) {
    // alert(this.dailyInspectionBean[name].isOk);
    this.dailyInspectionBean[name].isOk = !this.dailyInspectionBean[name].isOk;
    this.cd.detectChanges();
  }
  doIsNull(name){
    this.dailyInspectionBean[name].isOk = null;
    this.cd.detectChanges();
  }
  doError(name) {
    this.dailyInspectionBean[name].isOk = !this.dailyInspectionBean[name].isOk;
    // this.showOK = false;
    // this.showError = !this.showError;
  }
  doCamera(name, i) {
    let options: CameraOptions = {
      quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
      // encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      targetWidth: 1500,
      targetHeight: 1500,
      correctOrientation: true
    };
    this.camera.getPicture(options).then(
      imageData => {
        const options: FileUploadOptions = {};
        let serverUrl = encodeURI(
          appConfig.IP_URL + appConfig.API.upload
        );
        options.fileKey = "file";
        options.fileName = "test.jpg";
        options.mimeType = "image/jpeg";
        const fileTransfer: FileTransferObject = this.transfer.create();
        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
          let aa = JSON.parse(restul["response"]);
          if (aa["status"] == 200) {
            if (aa["data"].length > 0) {
              if (i == "c") {
                this.dailyInspectionBean[name].picUrl.push(aa["data"]);
              } else {
                this.dailyInspectionBean[name].picUrl[i] = aa["data"];
              }
            }
          }
          this.cd.detectChanges();
        });
      },
      err => {
        // Handle error
      }
    );
  }

  onHold(name, param) {
    let actionSheet = this.ActionSheet.create({
      buttons: [
        {
          text: "重拍",
          role: "重拍",
          handler: () => {
            let i = this.dailyInspectionBean[name].picUrl.indexOf(param);
            this.doCamera(name, i);
          }
        },
        {
          text: "查看大图",
          role: "查看大图",
          handler: () => {
            let url: string = param;
            this.photoViewer.show(
              encodeURI(
                this.appConfig.IP_URL + this.appConfig.API.getUpload + url
              ).replace("%5C", "/"),
              null,
              { share: false }
            );
          }
        },
        {
          text: "删除",
          handler: () => {
            let i = this.dailyInspectionBean[name].picUrl.indexOf(param);
            this.dailyInspectionBean[name].picUrl.splice(i, 1);
          }
        },
        {
          text: "取消",
          role: "取消",
          handler: () => { }
        }
      ]
    });
    actionSheet.present();
  }

  doSubmit() {
    if (this.commonFunc.vlidate(this.dailyInspectionBean, [], false)) {
      this.dailyInspectionBean.elevatorId = this.navParams.get("elevatorId");
      this.dailyInspectionBean.checkStartDt = moment(
        this.navParams.get("data")
      ).format("YYYYMMDDHHmmss");
      this.dailyInspectionBean.isUnusual = "0";
      if (JSON.stringify(this.dailyInspectionBean).includes("false")) {
        this.dailyInspectionBean.isUnusual = "1";
      }
      this.dailyInspectionBean.checkUserId = this.user.id;
      let param = this.commonFunc.convertBeanToString(this.dailyInspectionBean);
      this.storage.set("dailyinspection", param);
      this.navCtrl.push(WorkSumPage, {
        ElevaType: "daily",
        data: this.navParams.get("data"),
        elevatorInfo: this.navParams.get('elevatorInfo'),
      });
    } else {
      let toas = this.commonFunc.showInsideErrorToast({
        errorMessage: "请填写打x项说明"
      });
      toas.present();
      return;
    }
  }
}
